package com.bone.eventsweb.common;

import cn.hutool.core.util.StrUtil;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.bone.eventsweb.dao.UserDao;
import com.bone.eventsweb.entity.UserEntity;
import com.bone.eventsweb.exception.ServiceException;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class JwtInterceptor implements HandlerInterceptor {


    @Resource
    private UserDao userDao;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
       String token = request.getHeader("token");//从 header请求头里传来的参数
       if (StrUtil.isBlank(token)){
           token = request.getParameter("token"); //url 参数  ?token=xxxx
       }

       //如果不是映射到方法上直接放行 通过
//        if(handler instanceof HandlerMethod) {
//            AuthAccess annotation = ((HandlerMethod) handler).getMethodAnnotation(AuthAccess.class);
//            if (annotation != null) {
//                return true;
//            }
//        }


        //执行认证
        if (StrUtil.isBlank(token)) {
            throw new ServiceException("401","请登录");
        }


        //获取到token中的 user  id
        String userId;

        try {
            userId = JWT.decode(token).getAudience().get(0);// JWT.decode（token） 解码
            System.out.println("JWTInterceptor userId = "+ userId);
        } catch (JWTDecodeException e) {
            throw new ServiceException("401","请进行登录");
        }

        //根据token中的userid查询数据库
        UserEntity user = userDao.selectById(Integer.valueOf(userId));
        if (user == null) {
            throw new ServiceException("401","请进行登录");
        }

        //用户密码加签验证 token
        //通过用户密码加密后生成一个验证器
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(user.getPassword())).build();

        try {
            jwtVerifier.verify(token); //验证token
        } catch (JWTVerificationException e) {
            throw new ServiceException("401","身份验证不合法，请重新登录");
        }
        return true;
    }








}
